<template>
  <view>
    <Loader :loading="loading" text="加载问卷中...">
    <view class="flex-col group">
      <!-- <view class="flex-col justify-start items-start section_4"> -->
      <view class="fixed-header">
        <progress
          :percent="progress"
          activeColor="#F26A77"
          backgroundColor="#FFFFFF"
          border-radius="8"
          active
          :active-mode="progressActiveMode"
          duration="20"
      /></view>
      <view class="flex-col mt-10">
        <question-card
          class="list-item mt-16"
          v-for="item in pageQuestions"
          :key="item.id"
          :id="'ques_' + item.id.toString()"
          :question="item"
          :number="questionNumbers[item.id]"
          :tf_options="config.tf_options"
          :answer="answers[item.id]"
          @update:answer="answers[item.id] = $event"
        ></question-card>
      </view>
      <view class="flex-row mt-16">
        <button class="button" hover-class="button-hover" @click="toPrevPage">
          {{ isFirstPage ? "返回" : "上一步" }}
        </button>
        <button
          class="button ml-10"
          hover-class="button-hover"
          @click="toNextPage"
        >
          {{ isLastPage ? "提交" : "下一步" }}
        </button>
      </view>
    </view>
    </Loader>
    <uni-popup ref="alertDialog" type="dialog" style="z-index: 100;">
      <uni-popup-dialog
        cancelText="取消"
        confirmText="确认"
        title="注意"
        content="问卷已完成，确认提交？"
        @confirm="submit"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="alertAnswerDialog" type="dialog">
      <uni-popup-dialog
        cancelText="重新开始"
        confirmText="继续"
        title="注意"
        content="检测到您上次未完成的问卷，是否继续？"
        @confirm="loadHistoryAnswers"
        @close="loadDefaultAnswers"
      ></uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="saveFailedDialog" type="dialog">
      <uni-popup-dialog
        cancelText="取消"
        confirmText="重新提交"
        title="保存失败"
        :content="saveFailedMessage"
        @confirm="retrySubmit"
        @close="handleSaveFailedClose"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import QuestionCard from "../../components/Questionnare/QuestionCard/QuestionCard.vue";
import Loader from "@/components/Loader/Loader.vue";
import {
  getQuestionnaire,
  toResult,
  initializeQuestionnaireSystem,
  getValidQuestionIds,
} from "../../util/questionnaire/index.js";

export default {
  components: {
    QuestionCard,
    Loader,
  },
  data() {
    return {
      config: {
        quesName: null,
        resultPage: null,
        tf_options: null,
      },
      quesName: null,
      questions: null,
      answers: null,
      slice: null,
      scoreJudge: null,
      loading: true,
      curPage: 0,
      progressActiveMode: "forwards",
      // refreshCards: true,
      saveFailedMessage: "问卷保存失败，请检查网络连接后重试。",
    };
  },
  computed: {
    pageNum() {
      return this.slice?.length ?? 1;
    },
    pageQuestions() {
      if (!this.questions || !this.answers) {
        console.log("pageQuestions: missing data", { 
          hasQuestions: !!this.questions, 
          hasAnswers: !!this.answers,
          questionsLength: this.questions?.length,
          answersLength: this.answers?.length
        });
        return [];
      }
      
      const validIds = this.getValidQuestionIds(this.slice[this.curPage], ["visible"]);
      console.log("pageQuestions: validIds", {
        curPage: this.curPage,
        slice: this.slice[this.curPage],
        validIds,
        answers: this.answers
      });
      
      return validIds.map((id) => this.questions[id]);
    },
    questionNumbers() {
      const valid_ids = this.getValidQuestionIds(
        Array.from({ length: this.questions.length }, (_, i) => i),
        ["visible", "plain"]
      );
      const questionNums = this.questions.map((item) => {
        const index = valid_ids.indexOf(item.id);
        return index >= 0 ? index + 1 : -1;
      });
      return questionNums;
    },
    progress() {
      if (!this.answers) return 0;
      const valid_answers = this.getValidQuestionIds(
        Array.from({ length: this.questions.length }, (_, i) => i),
        ["visible", "plain"]
      ).map((id) => this.answers[id]);
      console.log("valid_answers", valid_answers);
      let answered = valid_answers.filter((item) => item !== "").length;
      const res = Math.min((answered / valid_answers.length) * 100 + 1, 100);
      console.log("progress updated", res);
      return res;
    },
    isFirstPage() {
      return this.getPrevPage() < 0;
    },
    isLastPage() {
      return this.getNextPage() >= this.pageNum;
    },
  },

  watch: {
    answers: {
      handler(newAnswers) {
        console.log("answers changed");
        this.$storage.set(`ans_${this.quesName}`, newAnswers);
      },
      deep: 1,
    },
  },

  methods: {
    loadQuestionnaire() {
      try {
        const res = getQuestionnaire(this.quesName);
        if (!res) {
          throw new Error(`未找到问卷: ${this.quesName}`);
        }
        this.questions = res.questions;
        this.slice = res.slice;
        this.scoreJudge = res.score_judge;
        this.config.resultPage = res.result_page;
        this.config.tf_options = res.tf_options;
        uni.setNavigationBarTitle({
          title: res.title,
        });
        console.log("Get questionnaire: ", this.questions);
      } catch (err) {
        console.log("Fail to load questionnaire: ", err);
      }
    },
    getHistory() {
      const ans = this.$storage.get(`ans_${this.quesName}`);
      console.log("Get history: ", ans);
      if (ans && ans.some((item) => item !== "")) {
        this.$refs.alertAnswerDialog.open();
      } else {
        this.loadDefaultAnswers();
      }
    },
    loadHistoryAnswers() {
      const ans = this.$storage.get(`ans_${this.quesName}`);
      console.log("Load answers: ", ans);
      if (ans) {
        this.answers = ans;
        // 切换到上次答题的页面
        this.loadPageProgress();
      } else {
        this.answers = Array(this.questions.length).fill("");
      }
      this.loading = false;
    },
    loadDefaultAnswers() {
      this.answers = Array(this.questions.length).fill("");
      this.loading = false;
    },
    loadPageProgress() {
      const last_answered_id = this.answers.findLastIndex(
        (item) => item !== ""
      );
      const last_answered_page = this.slice.findIndex((item) =>
        item.includes(last_answered_id)
      );
      if (last_answered_page >= 0) this.curPage = last_answered_page;
      this.$nextTick(() => {
        uni.pageScrollTo({
          selector: "#ques_" + last_answered_id.toString(),
        });
      });
    },
    // 过滤前置条件不满足的问题
    getValidQuestionIds(ids, filters = ["visible"]) {
      const result = getValidQuestionIds(
        ids,
        filters,
        this.answers,
        this.questions
      );
      
      return result;
    },
    getNextPage() {
      let has_problem = false;
      let curPage = this.curPage;
      // Skip empty pages
      do {
        curPage++;
        if (curPage == this.pageNum) {
          return curPage;
        }
        const valid_ids = this.getValidQuestionIds(this.slice[curPage], [
          "visible",
        ]);
        has_problem = valid_ids.length > 0;
      } while (!has_problem);
      return curPage;
    },
    getPrevPage() {
      let has_problem = false;
      let curPage = this.curPage;
      // Skip empty pages
      do {
        curPage--;
        if (curPage < 0) {
          return curPage;
        }
        const valid_ids = this.getValidQuestionIds(this.slice[curPage], [
          "visible",
        ]);
        has_problem = valid_ids.length > 0;
      } while (!has_problem);
      return curPage;
    },
    toNextPage() {
      console.log(this.answers);
      console.log(this.pageQuestions);
      // check if all questions are answered
      for (const item of this.pageQuestions) {
        if (item.type === "plain") continue;
        if (this.answers[item.id] === "") {
          uni.showToast({
            title: "第" + this.questionNumbers[item.id] + "题尚未回答",
            icon: "none",
          });
          return;
        }
      }
      // to next page or get result
      const nextPage = this.getNextPage();
      if (nextPage < this.pageNum) {
        this.curPage = nextPage;
        uni.pageScrollTo({
          scrollTop: 0,
        });
      } else {
        this.toResult();
      }
    },
    toPrevPage() {
      const prevPage = this.getPrevPage();
      if (prevPage >= 0) {
        // skip empty pages
        this.curPage = prevPage;
        uni.pageScrollTo({
          scrollTop: 0,
        });
      } else {
        uni.navigateBack();
      }
    },
    toResult() {
      this.$refs.alertDialog.open();
    },
    submit() {
      const eventChannel = this.getOpenerEventChannel();
      
      // 监听保存失败事件
      if (eventChannel) {
        eventChannel.on('saveFailed', (data) => {
          console.log('Save failed:', data);
          this.saveFailedMessage = `问卷保存失败：${data.error?.message || '网络连接异常'}，请检查网络连接后重试。`;
          this.$refs.saveFailedDialog.open();
        });
      }
      
      // 调用结果函数
      toResult(this.quesName, this.answers, eventChannel);
    },
    retrySubmit() {
      // 重新提交问卷
      this.submit();
    },
    handleSaveFailedClose() {
    },
  },

  onLoad(options) {
    if (!options.ques) {
      console.error("Error: no quesName in options");
      uni.navigateBack();
      return;
    }
    this.quesName = options.ques;
    this.config.quesName = this.quesName;
    console.log("Questionare name: ", this.quesName);
  },

  async mounted() {
    // 初始化问卷系统（包括异步获取用户信息）
    await initializeQuestionnaireSystem();
    
    this.loadQuestionnaire();
    this.getHistory();
  },
};
</script>

<style scoped lang="css">
.group {
  padding: 24rpx 35rpx 0;
}

.section_4 {
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.section_5 {
  background-color: #f26a77;
  border-radius: 16rpx;
  width: 480rpx;
  height: 12rpx;
}

.list-item:first-child {
  margin-top: 0;
}

.button {
  align-self: stretch;
  width: 640rpx;
  background-color: #f26a77;
  color: #ffffff;
  border-radius: 16rpx;
}

.button-hover {
  background-color: #e56571;
}

.fixed-header {
  position: fixed; 
  top: 0;
  left: 0;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>

<style>
page {
  background-color: #f5f5f5;
  padding-bottom: 50rpx;
}
</style>